﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Npgsql;

/// <summary>
/// Database 的摘要说明
/// </summary>
public class DatabaseOper
{
	public DatabaseOper()
	{
       
	}

    ~DatabaseOper()
    {
        
    }

    Npgsql.NpgsqlConnection _connection;

    public void OpenConnection(string databaseName, string server, int port, string userId, string password)
    {
        string sConn = string.Format("DATABASE={0};SERVER={1};PORT={2};UID={3};PWD={4}", databaseName, server, port.ToString(), userId, password);

        try
        {
            if (this._connection == null)
                this._connection = new NpgsqlConnection(sConn);

            if (this._connection.State == ConnectionState.Closed)
                this._connection.Open();
        }
        catch
        {
            throw new Exception("数据库连接错误");
        }

    }

    public void CloseConnection()
    {
        if (this._connection != null && this._connection.State != ConnectionState.Closed)
        {
            this._connection.Close();
            this._connection = null;
        }
    }

    public DataTable GetDataFromDatabase(string sqlString)
    {
        this.OpenConnection(GlobeVaribles.DBDatabaseName, GlobeVaribles.DBServer, GlobeVaribles.DBPort, GlobeVaribles.DBUserName, GlobeVaribles.DBPassword);

        if (this._connection == null) throw new Exception("数据库连接发生错误。。。");

        NpgsqlDataAdapter oDataAdpater = null;
        DataTable dtResult = new DataTable();

        try
        {
            oDataAdpater = new NpgsqlDataAdapter(sqlString, this._connection);
            oDataAdpater.Fill(dtResult);
        }
        finally
        {
            this.CloseConnection();

            if (oDataAdpater != null)
            {
                oDataAdpater.Dispose();
                oDataAdpater = null;
            }
        }

        return dtResult;
    }

    public object GetStatisticValueFromDatabase(string sqlString)
    {
        this.OpenConnection(GlobeVaribles.DBDatabaseName, GlobeVaribles.DBServer, GlobeVaribles.DBPort, GlobeVaribles.DBUserName, GlobeVaribles.DBPassword);

        if (this._connection == null) throw new Exception("数据库连接发生错误。。。");

        Npgsql.NpgsqlCommand oCmd = null;
        object oResult = null;

        try
        {
            oCmd = new NpgsqlCommand(sqlString, this._connection);
            oResult = oCmd.ExecuteScalar();
        }
        finally
        {
            this.CloseConnection();

            if (oCmd != null)
            {
                oCmd.Dispose();
                oCmd = null;
            }
        }

        return oResult;
    }
}
